package chc

import (
	"fmt"
	"strings"

	"github.com/ClickHouse/clickhouse-go"
	"github.com/jmoiron/sqlx"
)

func connection(config *Config) (err error) {

	params := config.getConnectionParams()
	if chSession.Connect, err = sqlx.Open("clickhouse", fmt.Sprintf("tcp://%s%s", config.Host, params+config.getConnectionAltHostsParams())); nil != err {
		return err
	}

	if err = chSession.Connect.Ping(); nil != err {
		if exception, ok := err.(*clickhouse.Exception); ok {
			_ = fmt.Errorf("[%d] %s \n%s\n", exception.Code, exception.Message, exception.StackTrace)
		}
		return err
	}

	signleConn(chSession.Config, params)

	return nil
}

func signleConn(config *Config, param string) {

	var (
		connect *sqlx.DB
		err     error
	)

	if connect, err = sqlx.Open("clickhouse", fmt.Sprintf("tcp://%s%s", config.Host, param)); nil != err {
		fmt.Println("Single connection host failure")
	} else {
		chSession.SingleConns = append(chSession.SingleConns, connect)
	}

	altHosts := strings.Split(strings.ReplaceAll(config.AltHosts, " ", ""), ",")
	for _, altHost := range altHosts {
		if "" == altHost {
			continue
		}

		if connect, err = sqlx.Open("clickhouse", fmt.Sprintf("tcp://%s%s", altHost, param)); nil != err {
			_ = fmt.Errorf("Single connection host failure\n")
		} else {
			chSession.SingleConns = append(chSession.SingleConns, connect)
		}
	}
}
